package com.shop.server.controller;


import com.alibaba.fastjson.JSON;
import com.shop.common.constant.CookieConstant;
import com.shop.common.entity.CommonResult;
import com.shop.common.pojo.User;
import com.shop.server.service.LoginService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-10-30
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 获取登录用户信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/name")
    public CommonResult name(@CookieValue(name = "login_token", required = false) String token) {
        try {
            return loginService.loginName(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult(false, "redis超时或出异常了", "网络繁忙，请刷新下页面");
    }

    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 登录
     *
     * @param map
     * @param response
     * @return
     */
    @PostMapping("/do")
    public CommonResult login(@RequestBody Map map,
                              @CookieValue(name = CookieConstant.CART_TOKEN) String cookieCartToken,
                              HttpServletResponse response) {

        try {
            CommonResult<User> result = loginService.login(map);
            String uuid = result.getMessage();
            //Cookie login_token=uuid
            Cookie cookie = new Cookie(CookieConstant.LOGIN_TOKEN, uuid);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            cookie.setPath("/");
            response.addCookie(cookie);

            //合并购物车【时间会点长】: 异步【RabbitMQ】
            //传 未登录购物车cookie 和 已登录用户的ID
            Map<String, Object> msgMap = new HashMap();
            msgMap.put("cart_token",cookieCartToken);
            msgMap.put("login_token",uuid);
            //System.out.println(response.getClass());
            //msgMap.put("resp", response);

            String message = JSON.toJSONString(msgMap);

            rabbitTemplate.convertAndSend("cookieExchange", "cart_token.delete", message);

            //删除购物车的cookie，合并购物车业务可以使用手动ack确定完成
            Cookie cartToken = new Cookie(CookieConstant.CART_TOKEN, "");
            cartToken.setPath("/");
            cartToken.setMaxAge(0);
            response.addCookie(cartToken);

            return new CommonResult("登录成功", result.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new CommonResult(false, "登录失败", "用户登录信息错误！！");

    }

}
